package com.javaisworkbench.javatree;

import org.drools.core.io.impl.UrlResource;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.KieScanner;
import org.kie.api.builder.ReleaseId;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import java.io.IOException;
import java.io.InputStream;

public class TestWorkBench {
    @Test
    public void test() throws IOException {
        String url
                = "http://localhost:8081/kie-drools-wb/maven2/com/javaisworkbench/javaIsWorkbench/1.0.0/javaIsWorkbench-1.0.0.jar";
        KieServices ks = KieServices.Factory.get();
        KieRepository kr = ks.getRepository();
        UrlResource urlResource = (UrlResource) ks.getResources().newUrlResource(url);
        urlResource.setUsername("kie");
        urlResource.setPassword("kie");
        urlResource.setBasicAuthentication("enabled");
        InputStream is = urlResource.getInputStream();
        KieModule kieModule = kr.addKieModule(ks.getResources().newInputStreamResource(is));
        KieContainer kieContainer = ks.newKieContainer(kieModule.getReleaseId());
        KieSession kieSession = kieContainer.newKieSession();
        Person person = new Person(30, "zhangsan");
        kieSession.insert(person);
        int i = kieSession.fireAllRules();
        System.out.println("java调用workbench 共执行了" + i + "条规则");
        System.out.println("修改后的结果" + person.getAge());
    }


    @Test
    public void runScanner() throws InterruptedException {
        KieServices ks = KieServices.Factory.get();
        ReleaseId releaseId = ks.newReleaseId("com.javaisworkbench", "javaIsWorkbench", "1.0.0");
        KieContainer kieContainer = ks.newKieContainer(releaseId);
        KieScanner kieScanner = ks.newKieScanner(kieContainer);
        kieScanner.start(10000L);
        while (true) {
            KieSession kieSession = kieContainer.newKieSession();
            Person person = new Person(30, "zhangsan");
            kieSession.insert(person);
            int i = kieSession.fireAllRules();
            System.out.println("java调用workbench 自动扫描共执行了" + i + "条规则");
            System.out.println("修改后的结果" + person.getAge());
            Thread.sleep(5000);
        }
    }
}
